package capitulo5;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.net.URL;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class DrawImage extends JFrame implements KeyListener{

	private Image image;
	private double scale = 0.5;
	private AffineTransform identity = new AffineTransform();
	
	public static void main(String[] args){
		new DrawImage();
	}
	
	public DrawImage(){
		super("DrawImage");
		setSize(800,600);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Toolkit tk = Toolkit.getDefaultToolkit();
		image = tk.getImage(getURL("castle.png"));
		addKeyListener(this);
	}
	
	private URL getURL(String filename){
		URL url = null;
		try {
			url = this.getClass().getResource(filename);
		} catch(Exception e) {}
		return url;
	}
	
	public void paint(Graphics g){
		// Create an instance of Graphics g
		Graphics2D g2d = (Graphics2D)g;
		
		// fill the background with black
		g2d.setColor(Color.BLACK);
		g2d.fillRect(0, 0, getSize().width, getSize().height);
		
		AffineTransform trans = new AffineTransform();
		trans.setTransform(identity);
		trans.translate(40,40);
		trans.scale(scale,scale);
		
		// draw the image
		g2d.drawImage(image,trans,this);
	}

	@Override
	public void keyPressed(KeyEvent k) {
		if (k.getKeyCode() == KeyEvent.VK_PLUS && scale <= 2.0){
			scale +=0.1;	
			repaint();
		} else if ((k.getKeyCode() == KeyEvent.VK_MINUS && scale >= 0.1)) {
			scale -=0.1;	
			repaint();
		}
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}
